'use client';

import React, { useState, useEffect } from 'react';
import { Card, Typography, Divider, Switch, message, Spin, Empty, Modal } from 'antd';
import Layout from '@/components/Layout';
import { getSystemSettings, updateSystemSetting, SystemSetting } from '@/lib/settings';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { Title, Paragraph } = Typography;
const { confirm } = Modal;

const SystemSettingsPage = () => {
  const [settings, setSettings] = useState<SystemSetting[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [updatingSettings, setUpdatingSettings] = useState<Set<number>>(new Set());

  // 获取系统设置
  const fetchSettings = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getSystemSettings();
      setSettings(data || []);
    } catch (error) {
      console.error('获取系统设置失败:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      setError(errorMessage);
      message.error('获取系统设置失败：' + errorMessage);
      setSettings([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSettings();
  }, []);

  // 处理设置变更
  const handleSettingChange = (setting: SystemSetting, checked: boolean) => {
    const action = checked ? '启用' : '禁用';
    
    confirm({
      title: `确认${action}设置`,
      icon: <ExclamationCircleOutlined />,
      content: `确定要${action}「${setting.settingName}」吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // 添加到更新集合
        setUpdatingSettings(prev => new Set(prev).add(setting.settingId));
        
        try {
          await updateSystemSetting(setting.settingId, checked ? 1 : 0);
          message.success(`${action}成功`);
          // 刷新设置
          await fetchSettings();
        } catch (error) {
          console.error('更新设置失败:', error);
          Modal.error({
            title: '更新失败',
            content: error instanceof Error ? error.message : '未知错误'
          });
        } finally {
          // 从更新集合中移除
          setUpdatingSettings(prev => {
            const next = new Set(prev);
            next.delete(setting.settingId);
            return next;
          });
        }
      }
    });
  };

  // 获取设置的描述
  const getSettingDescription = (settingName: string) => {
    const descriptions: Record<string, string> = {
      '部门是否连带删除': '删除部门时是否同时删除部门下的所有数据',
      // 可以添加更多设置的描述
    };
    return descriptions[settingName] || settingName;
  };

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Card>
          <Title level={2}>系统设置</Title>
          <Paragraph type="secondary">
            在这里管理系统的各项功能开关。修改后立即生效。
          </Paragraph>
          <Divider />
          
          {loading ? (
            <div style={{ textAlign: 'center', padding: '50px' }}>
              <Spin size="large" />
            </div>
          ) : error ? (
            <Empty
              description={
                <span style={{ color: '#ff4d4f' }}>
                  {error}
                  <br />
                  <a onClick={fetchSettings}>点击重试</a>
                </span>
              }
            />
          ) : settings.length === 0 ? (
            <Empty description="暂无系统设置" />
          ) : (
            <div>
              {settings.map(setting => (
                <div key={setting.settingId} style={{ marginBottom: '24px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <Title level={5} style={{ marginBottom: '4px' }}>{setting.settingName}</Title>
                      <Paragraph type="secondary" style={{ marginBottom: '0' }}>
                        {getSettingDescription(setting.settingName)}
                      </Paragraph>
                    </div>
                    <Switch
                      checked={setting.settingValue === '1'}
                      onChange={(checked) => handleSettingChange(setting, checked)}
                      loading={updatingSettings.has(setting.settingId)}
                    />
                  </div>
                  <Divider />
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>
    </Layout>
  );
};

export default SystemSettingsPage; 